package ext.vpde.cadvaulting.globalvault;

import ext.vpde.cadvaulting.util.*;

public class EN {
	
	public static void main (String [] args ) throws Exception {
		String item_number = args[0];
		item_number = item_number.toUpperCase();
		String rev_lvl = args[1];
		String item_num = (item_number.endsWith(".DRW")) ? item_number.substring(0,item_number.indexOf(".")) : item_number;
		String en = getEN(item_num,rev_lvl);
		//System.out.println("EN: " + en);
		setEN(item_number,rev_lvl,"1",en);
	}
	
	public static void addENToDocument(String item_number, String version, String iteration) throws Exception {
		item_number = item_number.toUpperCase();
		String item_num = (item_number.endsWith(".DRW")) ? item_number.substring(0,item_number.indexOf(".")) : item_number;
		String en = getEN(item_num,version);
		//System.out.println("EN: " + en);
		setEN(item_number,version,iteration,en);
	}
	
	public static String getEN(String item_number, String version) throws Exception {
		SJTCSQL.openConnection();
		String sqlStr = "select a.en_nbr from sjtcapp.end_en_detail a, sjtcapp.end_en_head b ";
		sqlStr += "where a.item_type_code='D' and ";
		sqlStr += "a.en_nbr=b.en_nbr and ";
		sqlStr += "b.status_code<>'DEL' and ";
		sqlStr += "b.en_type in ('normal', 'specification') and ";
		sqlStr += "a.item_nbr='" + item_number + "' and ";
		sqlStr += "a.rev_lvl='" + version + "'";
		String theEN = SJTCSQL.doSQLGet(sqlStr,true);
		SJTCSQL.closeConnection();
		return theEN;
	}
	
	public static void setEN(String docNumber, String version, String iteration, String en) throws Exception {
		WINDSQL.openConnection();
		String ida2a2 = WINDSQL.getIdFromDocumentNumber(docNumber, version, iteration);
		String sqlStr = "";
		if (enExists(ida2a2)) {
			sqlStr  = "update stringvalue set value='" + en + "' where ";
			sqlStr += "ida3a4=" + ida2a2 + " and ida3a6 in ";
			sqlStr += "(select ida2a2 from stringdefinition where name='com.whirlpool.EN')";
		} else {
			sqlStr  = "insert into stringvalue (IDA3A5,HIERARCHYIDA6,CLASSNAMEKEYA6,IDA3A6,CLASSNAMEKEYA4,IDA3A4,";
			sqlStr += "CREATESTAMPA2,MARKFORDELETEA2,MODIFYSTAMPA2,CLASSNAMEA2A2,IDA2A2,UPDATECOUNTA2,UPDATESTAMPA2,VALUE,VALUE2) ";
			sqlStr += "select 0,HIERARCHYID,CLASSNAMEA2A2,IDA2A2,'wt.epm.EPMDocument'," + ida2a2 + ",sysdate,0,";
			sqlStr += "sysdate,'wt.iba.value.StringValue'," + WINDSQL.getNextId() + ",1,sysdate,'" + en + "','" + en + "' ";
			sqlStr += " from stringdefinition where name='com.whirlpool.EN'";
		}
		WINDSQL.doSQLSave(sqlStr);
		WINDSQL.closeConnection();
	}
	
	public static boolean enExists(String ida2a2) throws Exception {
		String sqlStr = "select value from stringvalue where ida3a4=" + ida2a2 + " and ida3a6 in ";
		sqlStr += "(select ida2a2 from stringdefinition where name='com.whirlpool.EN')";
		return (WINDSQL.doSQLGet(sqlStr) != null) ? true : false;
	}
}
